import 'package:flutter/material.dart';

///
/// 页面保活
///
class KeepAliveFrame extends StatefulWidget {
  const KeepAliveFrame({Key? key}) : super(key: key);

  @override
  _KeepAliveFrameState createState() => _KeepAliveFrameState();
}

class _KeepAliveFrameState extends State<KeepAliveFrame> {
  List<String> _dataList = ["1", "2", "3", "4", "5"];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  void _reverse() {
    setState(() {
      _dataList = _dataList.reversed.toList();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: ListView.custom(
          childrenDelegate: SliverChildBuilderDelegate(
              (context, index) {
                return KeepAlive(
                    key: ValueKey<String>(_dataList[index]),
                    data: _dataList[index]);
              },
              childCount: _dataList.length,
              findChildIndexCallback: (Key key) {
                final ValueKey<String> valueKey = key as ValueKey<String>;
                final String data = valueKey.value;
                return _dataList.indexOf(data);
              }),
        ),
      ),
      bottomNavigationBar: BottomAppBar(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextButton(
                onPressed: () => _reverse(), child: const Text("Reverse items"))
          ],
        ),
      ),
    );
  }
}

class KeepAlive extends StatefulWidget {
  final String data;

  const KeepAlive({required Key key, required this.data}) : super(key: key);

  @override
  _KeepAliveState createState() => _KeepAliveState();
}

class _KeepAliveState extends State<KeepAlive>
    with AutomaticKeepAliveClientMixin {
  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Text(widget.data);
  }
}
